import os, time
from django.conf import settings


def SaveTempFile(file, filename):
    folder_path = settings.MEDIA_ROOT
    # 判断图片文件夹是否存在
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    # 删除历史图片
    # now = int(time.time())
    # oldfiles = os.listdir(folder_path)
    # for oldfile in oldfiles:
    #     oldfile_path = os.path.join(folder_path, oldfile)
    #     try:
    #         if os.path.isfile(oldfile_path):
    #             last = int(os.stat(oldfile_path).st_atime)
    #             if now - last > 180:
    #                 os.remove(oldfile_path)
    #     except:
    #         pass

    full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename)
    with open(full_filename, 'wb+') as fb:
        for chunk in file.chunks():
            fb.write(chunk)
    return "%s%s" % (settings.MEDIA_URL, filename)
